import { InputItem, Button, Flex } from 'antd-mobile';
import { createForm } from 'rc-form';
import { PureComponent } from "react"
import renderCom, { comArr } from "../../utils/renderCom"
import "./MForm.less"
import { connect } from "dva"
import { isNull, isArrInStr, calcField, filterExp } from "../../utils/helper"
import MyDatasource from '../MWrapper/MyDataSource';
@createForm({
	onFieldsChange: (props, fields, allFields) => {
		let { defaultFormData, dispatch, formDataKey, formData, formRef, config = {} } = props;
		let { setFieldsValue, getFieldDecorator } = formRef;
		let { data_store = {} } = config;
		let { rules = [] } = data_store;
		let newObj = {};
		let changeItems = ",";
		//有些情况下(已知的情况 1、有组件有验证时) 一个form的key的值发生变化时  会执行两次change，当某个key的dirty=false时(正常情况下为true 或者没有) 说明是第二次执行change 此时之后的逻辑就不需要执行
		let isDirty = true, isReset = false;
		for (let item in fields) {
			let { name, value, dirty } = fields[item];
			if (dirty === true) {
				isDirty = false;
			}
			changeItems += name + ",";
			//如果没有value这个属性 说明是重置
			if (!fields[item].hasOwnProperty("value")) {
				newObj[name] = defaultFormData[name];
				isReset = true
			}
			else {
				newObj[name] = value
			}
		}
		if (!isDirty) {
			return;
		}
		formData = {
			...formData,
			...newObj
		};
		//rules 就是需要监听某个key变化后执行的操作的数组
		if (rules instanceof Array && rules.length > 0) {
			rules.map(i => {
				let { on_change, condition, event } = i;
				//判断event配置是否存在 如果不存在就不向下执行
				if (event) {
					//判断on_change中的字段是否在改变的字段中
					if (isArrInStr(on_change, changeItems)) {
						// console.log("isIn");
						let isOk = true;
						//判断condition是否满足条件
						if (!isNull(condition)) {
							isOk = calcField(condition, formData)
						}
						if (isOk) {
							// console.log("isOk");
							let type = event.type;//事件的类型
							if (type == "formula") {//calc计算
								let { formula, key } = event;
								let val = eval(filterExp(formula, "formData"));
								getFieldDecorator(key);
								setFieldsValue({
									[key]: val
								})
							}
							if (type == "function") {//执行函数
								let { func } = event;
								try {
									eval("(" + func + ")")()
								}
								catch (e) {
									console.log(e);
								}
							}
							if (type == "api") {//请求api 返回结果赋给组件
								let { api, mapping } = event;
								dispatch({
									type: "form/rulesApi",
									payload: {
										apiInfo: api,
										data: formData,
										callback: (result) => {
											let { data, error } = result;
											if (error) {
												data = {}
											}
											if (!isNull(mapping)) {
												if (isReset) {
													data = formData;
													for (let m in mapping) {
														getFieldDecorator(m);
														setFieldsValue({
															[m]: data[m]
														})
													}
												}
												else {
													for (let m in mapping) {
														let k = mapping[m];
														getFieldDecorator(m);
														setFieldsValue({
															[m]: data[k]
														})
													}
												}
											}
										}
									}
								})
							}
							if (type == "data_source") {//请求数据源
								let { id, api, options, source_type } = event;
								dispatch({
									type: "form/getDataSource",
									payload: {
										dataset_key: id,
										source_type,
										options,
										apiInfo: api,
										data: newObj,
										formDataKey
									}
								})
							}
						}
					}
				}
			})
		}
		dispatch({
			type: "form/setFormData",
			payload: {
				key: formDataKey,
				value: newObj
			}
		})
	}
})
export default class MSearchForm extends PureComponent {
	constructor(props) {
		super(props);
		this.state = {
			isReset: false
		}
	}

	componentWillReceiveProps(next) {
		let { listFormData: data1, open: open1 } = this.props;
		let { listFormData: data2, open: open2 } = next;
		let { setFieldsValue, getFieldValue, resetFields } = next.form;
		//listFormData为列表页的formData
		if (open1 !== open2) {
			if (open2 === false) {
				console.log("关闭");
				//关闭高级搜索的form时，把form中的组件值重置
				setTimeout(() => {
					resetFields();
					let { dispatch, formDataKey, listFormData } = this.props;
					dispatch({
						type: "form/resetFormData",
						payload: {
							key: formDataKey
						}
					})
				}, 100)
			}
			if (open2 === true) {
				//打开高级搜索的form时，把列表页中的formData赋给form
				console.log("打开");
				for (let i in data2) {
					getFieldValue(i);
					setFieldsValue({
						[i]: data2[i]
					})
				}
			}
		}
	}
	componentWillReceiveProps1(next) {
		let { open: open1 } = this.props;
		let { open: open2 } = next;
		if (open1 !== open2 && open2 === false) {
			console.log("关闭");
			let { dispatch, formDataKey, listFormData } = this.props;
			dispatch({
				type: "form/resetFormData",
				payload: {
					key: formDataKey
				}
			})
		}
	}
	componentWillMount() {
		const { defaultFormData, dispatch, formDataKey } = this.props;
		dispatch({
			type: "form/setFormData",
			payload: {
				key: formDataKey,
				value: defaultFormData
			}
		})
	}
	componentDidMount() {
		let { listFormData } = this.props;
		let { setFieldsValue, getFieldValue } = this.props.form;
		for (let i in listFormData) {
			getFieldValue(i);
			setFieldsValue({
				[i]: listFormData[i]
			})
		}
	}
	handleSubmit = () => {
		let { validateFields } = this.props.form;
		let { submitFunc } = this.props;
		validateFields((error, value) => {
			if (!error) {
				submitFunc && submitFunc()
			}
			else {
				console.log(error);
			}
		})
	};
	resetFunc = () => {
		let { resetFields } = this.props.form;
		resetFields();
		this.setState({
			isReset: true
		});
		setTimeout(() => {
			this.setState({
				isReset: false
			})
		})
	};
	render() {
		const { getFieldDecorator, setFieldsValue, getFieldValue } = this.props.form;
		let { isReset } = this.state;
		let { config, dispatch, fd, formDataKey, formData, defaultFormData } = this.props;
		let { widgets, data_store, options, datasets } = config;
		let { content } = widgets;
		let el = [];
		let dataSets = [];
		let dataSourceObj = {
			formDataKey,
			getFieldValue,
			setFieldsValue,
			isReset
		};
		if (datasets) {
			for (let i in datasets) {
				let item = datasets[i];
				dataSets.push(
					<MyDatasource key={i} {...item} {...dataSourceObj} id={i} didFormData={formData} />
				)
			}
		}
		for (let i in content) {
			let item = content[i];
			let visible = item.visible;
			if (visible !== "0" && visible !== 0 && visible !== false) {
				if (comArr[item.component_type]) {
					let className = "page-item";
					if (item.new_group == 1) {
						className += " new_group"
					}
					if (item.component_type == "mi-group") {
						className += " mi-group"
					}
					el.push(<div key={i} className={className}>
						{
							renderCom({
								isSearch: true,
								model: "form",
								...item,
								...options,
								formData,
								defaultFormData,
								getFieldDecorator,
								setFieldsValue,
								isReset,
								dispatch,
								fd,
								formDataKey,
								setFormData: (value) => {
									dispatch({
										type: "form/setFormData",
										payload: {
											key: formDataKey,
											value
										}
									})
								}
							})
						}
					</div>)
				}
			}
		}
		return (
			<div className="mform" data-flex="dir:top box:last" style={{ height: "100%" }}>
				<div style={{ overflow: "auto" }}>
					{dataSets}
					{el}
				</div>
				<Flex justify="center" flex-box="0" className="footerButtons searchFromButtons">
					<Flex.Item>
						<Button onClick={this.resetFunc} style={{ height: "35px", lineHeight: '35px' }}>重置</Button>
					</Flex.Item>
					<Flex.Item>
						<Button type="primary" onClick={this.handleSubmit} style={{ height: "35px", lineHeight: '35px' }}>搜索</Button>
					</Flex.Item>
				</Flex>
			</div>
		)
	}
}